package com.hong.dao.Impl;

import com.hong.dao.BaseDao;
import com.hong.dao.OssDao;
import com.hong.entity.Oss;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class OssDaoImpl extends BaseDao implements OssDao {

    @Override
    public List<Oss> selectAll() {
        String sql = "SELECT * FROM `oss` ";
        ResultSet resultSet = executeQuery(sql);
        List<Oss> ossList = new ArrayList<>();
        if(resultSet !=null){
            try {
                while (resultSet.next()){
                    Oss oss  = new Oss();
                    oss.setId(resultSet.getInt("id"));
                    oss.setBucketName(resultSet.getString("bucketName"));
                    oss.setType(resultSet.getString("type"));
                    oss.setCapacity(resultSet.getInt("capacity"));
                    oss.setFlow(resultSet.getInt("flow"));
                    oss.setVisits(resultSet.getInt("visits"));
                    oss.setPermission(resultSet.getString("permission"));
                    ossList.add(oss);
                }
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                closedAll(resultSet);
            }
        }
        return ossList;
    }

    @Override
    public Oss ossListName(String bucketName) {
        String sql = "SELECT * FROM oss WHERE bucketName = ? ";
        ResultSet resultSet = executeQuery(sql, bucketName);
        if (resultSet != null) {
            try {
                while (resultSet.next()) {
                    Oss oss = new Oss();
                    oss.setId(resultSet.getInt("id"));
                    oss.setBucketName(resultSet.getString("bucketName"));
                    oss.setType(resultSet.getString("type"));
                    oss.setCapacity(resultSet.getInt("capacity"));
                    oss.setFlow(resultSet.getInt("flow"));
                    oss.setVisits(resultSet.getInt("visits"));
                    oss.setPermission(resultSet.getString("permission"));
                    return oss;
                }
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                closedAll(resultSet);
            }
        }
        return null;
    }

    @Override
    public int addOss(Oss oss) {
        StringBuilder sb = new StringBuilder();
        sb.append(" INSERT into oss(bucketName,type,permission) ");
        sb.append(" VALUES (?,?,?)");
        return executeUpdate(sb.toString(),oss.getBucketName(),oss.getType(),oss.getPermission());
    }

    @Override
    public int updatePermission(String bucketName, String permission) {
        String sql = "UPDATE oss SET permission = ? WHERE id = ? ";
        return executeUpdate(sql,permission,bucketName);
    }
}
